#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo 
@File    ：handler.py
@Author  ：赵加响
@Date    ：2023/6/28 17:05 
@Desc    ：邮件发送
"""
from pathlib import Path

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

from utils.email.constants import DEFAULT_TEMP


def send_email(subject, sender, recipient_list, template_path=DEFAULT_TEMP, context={}, cc_list=[], bcc_list=[],
               attachment_path=None):
    """
    发送邮件函数

    :param subject: 邮件主题
    :param sender: 发件人邮箱
    :param recipient_list: 收件人邮箱列表
    :param template_path: 邮件正文模板路径
    :param context: 邮件正文模板上下文数据
    :param cc_list: 抄送邮箱列表，默认为空列表
    :param bcc_list: 密送邮箱列表，默认为空列表
    :param attachment_path: 附件路径，默认为None
    """
    # 加载邮件正文模板并渲染上下文数据
    html_content = render_to_string(template_path, context)

    # 将 HTML 正文转换为纯文本
    text_content = strip_tags(html_content)

    # 创建 EmailMultiAlternatives 对象
    email = EmailMultiAlternatives(subject, text_content, sender, recipient_list, cc=cc_list, bcc=bcc_list)

    # 添加 HTML 正文
    email.attach_alternative(html_content, 'text/html')

    # 添加附件
    if attachment_path is not None:
        with open(attachment_path, 'rb') as f:
            attachment_data = f.read()
            attachment_name = Path(attachment_path).name
            email.attach(attachment_name, attachment_data)

    # 发送邮件
    return email.send()
